package com.agenda.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import com.agenda.model.Compromisso;
import com.agenda.model.Convite;

public class CompromissoController extends DefaultController<Compromisso> {

	private static CompromissoController INSTANCIA;

	private CompromissoController() {
		super("compromissos.dat");
	}

	public static CompromissoController getINSTANCIA() {
		if (INSTANCIA == null)
			INSTANCIA = new CompromissoController();

		return INSTANCIA;
	}

	@Override
	protected void preGravacao(Compromisso model) {

		if (model.getId().intValue() == 0)
			model.setId(getRegistrosSemSemaforo().size() + 1);
		/*else {
			Compromisso compromissoServer = buscarCompromisso(model.getId());
			for (Convite convite : model.getConvites()) {
				Convite conviteServer = compromissoServer.getConvite(convite.getUsuario());
				if (conviteServer != null)
					convite.setResposta(conviteServer.getResposta());
			}
		}*/

	}

	public List<Compromisso> getProximosCompromissos() {

		return getProximosCompromissos(new Date());
	}

	public List<Compromisso> getProximosCompromissos(Date data) {

		List<Compromisso> compromissos = new ArrayList<Compromisso>();
		List<Compromisso> compromissosBanco = getRegistros();

		for (Compromisso compromisso : compromissosBanco)
			if (!compromisso.getDataInicial().before(data))
				compromissos.add(compromisso);

		Collections.sort(compromissos);
		return compromissos;
	}

	public void confirmarRecusar(Compromisso compromisso, Convite convite) {
		try {
			semaforo.DOWN();

			Compromisso compromissoServer = buscarCompromisso(compromisso.getId());
			if (compromissoServer != null) {
				Convite conviteServer = compromissoServer.getConvite(convite.getUsuario());
				conviteServer.setResposta(convite.getResposta());

				int countConfirmado = 0;
				for (Convite conviteBanco : compromissoServer.getConvites()) {
					if (conviteBanco.getResposta() == Convite.ACEITO)
						countConfirmado++;
				}

				int size = compromissoServer.getConvites().size();
				if (size > 0) {
					float result = (float) countConfirmado / size;
					if (result >= 0.75)
						compromissoServer.setConfirmado(true);
					else
						compromissoServer.setConfirmado(false);
				} else {
					compromissoServer.setConfirmado(true);
				}

				gravarSemSemaforo(compromissoServer);
			}

		} finally {
			semaforo.UP();
		}

	}

	private Compromisso buscarCompromisso(Integer id) {
		List<Compromisso> compromissos = getRegistrosSemSemaforo();
		for (Compromisso compromisso : compromissos) {
			if (compromisso.getId().equals(id))
				return compromisso;
		}
		return null;
	}
}
